import { Component, OnInit, Injector, ViewChild, EventEmitter, Output } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/primeng';
import {
    ListDtoExtensionsItem,
    CheckResult,
    Stock_AccountBaseListDto,
    StockZT_RoomServiceProxy,
    StockZT_ToolTransferServiceProxy,
    Stock_ToolingTransferItemListDto,
    Stock_ToolingTransferItemEditDto,
    Stock_ToolingTransferBaseEditDto,
    StockZT_TransfersBillItemServiceProxy,
    StockZT_OutBillItemServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
// import { Cost_ProdQCCardListDto } from '@shared/service-proxies/cost-service-proxies';
import {
    UserDataPermissionServiceProxy,
    SessionServiceProxy,
    ComboboxItemDto
} from '@shared/service-proxies/stock-service-proxies';
import { SimpleAccountBaseInfoModalComponent } from '@app/shared/common/stockbase/account-base-info-modal.component';
import { LabelValue } from '@shared/service-proxies/stock-service-proxies';
interface ISelectedItems {
    label: string;
    value: string;
}
@Component({
    templateUrl: './create-or-edit-tooling-transfer-modal.component.html',
    animations: [appModuleAnimation()],
    selector: 'createOrEditToolingTransferModal'
})
export class CreateOrEditToolingTransferModalComponent extends AppComponentBase implements OnInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('simpleAccountBaseInfoModal') simpleAccountBaseInfoModal: SimpleAccountBaseInfoModalComponent;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Output() modalUpdate: EventEmitter<any> = new EventEmitter<any>();
    @Output() accountShow: EventEmitter<any> = new EventEmitter<any>();
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;
    f_OperatorDate: Date;
    f_ToOperatorDate: Date;

    selectedBill: Stock_ToolingTransferItemListDto;
    billbase = new Stock_ToolingTransferBaseEditDto();
    f_OutDept: LabelValue;
    miliOutBillList = new Array<Stock_ToolingTransferItemListDto>();
    f_MaterialTypeOptions;
    recipientsNatureOptions;
    //qccard: Cost_ProdQCCardListDto;
    f_currentDeptId; //当前部门Id
    f_currentDeptName; //当前部门名称
    optionOutDept; //调出单位
    optionOutKeeper; //调出单位保管员
    optionOutAccounting; //调出单位会计
    optionOutLeader; //调出单位领导
    optionInLeader; //调入单位领导
    optionInKeeper; //调入单位保管员
    optionInAccounting; //调度单位会计
    //审批人如果不存在下拉列表中，先增加，关闭或打开页面时删除
    optionInLeaderPush;
    optionInAccountingPush;
    optionOutKeeperPush;

    selectOutDept: LabelValue; //调出单位
    selectOutKeeper; //调出单位保管员
    selectOutAccounting; //调出单位会计
    selectOutLeader; //调出单位领导
    selectInLeader; //调入单位领导
    selectInKeeper; //调入单位保管员
    selectInAccounting; //调度单位会计
    f_indept; //调入单位
    selecttept;
    f_StorageAreaCodeOption = []; //库位
    oldOutDept;
    closed = false;
    constructor(
        injector: Injector,
        private _base_SessionServiceProxy: SessionServiceProxy,
        private _billService: StockZT_ToolTransferServiceProxy,
        private _tranbillService: StockZT_TransfersBillItemServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy,
        private _intobillService: StockZT_OutBillItemServiceProxy
    ) {
        super(injector);
    }
    active = false;
    saving = false;
    billid = '';
    rooms;
    code: CheckResult;
    itemid;
    editBill: Stock_ToolingTransferItemListDto;
    billName = "";
    isEidtItem = false;
    PlanNumber = '';
    ContractNumber = '';
    ngOnInit() {
        //当前部门名称
        this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
            // this._billService.getCurrentDeptName().subscribe(result => {
            this.f_currentDeptName = result.label;
            this.f_currentDeptId = result.value;
            //调入仓库
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result1 => {
                this.selecttept = result1.items;
                // this.itemContextMenuItems = this.getContextMenuItems();
                this._stockZT_RoomServiceProxy
                    .getRoomList('工装库', this.selecttept, result.label, undefined, 1000, 0)
                    .subscribe(result2 => {
                        this.rooms = result2.items.map(e => {
                            return {
                                label: e.f_WarehouseName,
                                value: e.f_WarehouseCode
                            };
                        });
                    });
            });
            //调入单位主管领导
            // this._tranbillService.getRoleUser('车间主任', result.value).subscribe(result => {
            //     this.optionInLeader = result.items.map(e => {
            //         return {
            //             label: e.displayText,
            //             value: e
            //         };
            //     });
            // });

            this._intobillService.getDeptIdByDeptCode('天津火箭').subscribe(result1 => {
                this._tranbillService.getRoleUser('工艺技术主管', result1.toString()).subscribe(result => {
                    this.optionInLeader = result.items.map(e => {
                        return {
                            label: e.displayText,
                            value: e
                        };
                    });
                });
            });
            this._intobillService.getDeptIdByDeptCode('天津火箭').subscribe(result1 => {
                this._tranbillService.getRoleUser('计划生产主管', result1.toString()).subscribe(result => {
                    this.optionInAccounting = result.items.map(e => {
                        return {
                            label: e.displayText,
                            value: e
                        };
                    });
                });
            });
            this.billbase.f_BillName = this.f_currentDeptName + '调拨单';
        });

        this._userDataPermissionServiceProxy.getUserSingleDataPermissions('ToolingTransfer').subscribe(result => {
            //调出单位
            this.optionOutDept = result.items.map(e => {
                return {
                    label: e.label,
                    value: e
                };
            });
            if (result.items.length > 0) {
                this.selectOutDept = result.items[0];
                this.changeInAccounting({ value: this.selectOutDept });
            }
        });
    }
    //调出单位改变事件
    changeInAccounting(event) {
        if (this.selectOutDept != this.oldOutDept) {
            if (this.billid == null || this.billid == undefined || this.billid == "") {
                let miliLen = this.miliOutBillList.filter(p => p.id == null).length
                if (miliLen > 0) {
                    let msg = "您已选择" + miliLen + "条数据，如果改变调出部门将删除这些数据,确定改变吗";
                    this.message.confirm(msg, isConfirmed => {
                        if (isConfirmed) {
                            this.miliOutBillList = new Array<Stock_ToolingTransferItemListDto>();
                            //调出单位保管员
                            this._tranbillService.getRoleUser('车间主任', event.value.value).subscribe(result => {
                                this.optionOutKeeper = result.items.map(e => {
                                    return {
                                        label: e.displayText,
                                        value: e
                                    };
                                });
                                this.oldOutDept = this.selectOutDept;
                            });
                        } else {
                            this.setSelectedOutDept(this.oldOutDept.label, this.oldOutDept.value, null, null);
                        }
                    });
                } else {
                    //调出单位保管员
                    this._tranbillService.getRoleUser('车间主任', event.value.value).subscribe(result => {
                        this.optionOutKeeper = result.items.map(e => {
                            return {
                                label: e.displayText,
                                value: e
                            };
                        });
                        this.oldOutDept = this.selectOutDept;
                    });
                }
            } else {
                this._billService.getToolingTransferCount(this.billid).subscribe(result => {
                    var count = this.miliOutBillList.filter(p => p.id == null).length + result;
                    if ((count) == 0) {
                        //调出单位保管员
                        this._tranbillService.getRoleUser('车间主任', event.value.value).subscribe(result => {
                            this.optionOutKeeper = result.items.map(e => {
                                return {
                                    label: e.displayText,
                                    value: e
                                };
                            });
                            this.oldOutDept = this.selectOutDept;
                        });
                    } else {
                        let msg = "该单下有" + count + "条数据，如果改变调出部门将删除这些数据,确定改变吗";
                        this.message.confirm(msg, isConfirmed => {
                            if (isConfirmed) {
                                this._billService.deleteToolingTransfer(this.billid).subscribe(() => {
                                    //调出单位保管员
                                    this._tranbillService.getRoleUser('车间主任', event.value.value).subscribe(result => {
                                        this.optionOutKeeper = result.items.map(e => {
                                            return {
                                                label: e.displayText,
                                                value: e
                                            };
                                        });
                                        this.miliOutBillList = new Array<Stock_ToolingTransferItemListDto>();
                                        this.oldOutDept = this.selectOutDept;
                                    });
                                });
                            } else {
                                this.setSelectedOutDept(this.oldOutDept.label, this.oldOutDept.value, null, null);
                            }
                        });
                    }
                });
            }
        }
        /* this.f_indept = event.value;
        //调出单位保管员
        this._tranbillService.getRoleUser('工装库存保管员', event.value.value).subscribe(result => {
            this.optionOutKeeper = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
        });
        //调出单位会计
        this._tranbillService.getRoleUser('车间财务', event.value.value).subscribe(result => {
            this.optionOutAccounting = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
        });
        //调出单位领导
        this._tranbillService.getRoleUser('车间主任', event.value.value).subscribe(result => {
            this.optionOutLeader = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
        }); */
    }
    show(id?: string, billitem?: Stock_ToolingTransferItemListDto): void {
        this.closed = false;
        this.active = true;
        this.billid = id;
        this.f_OperatorDate = new Date();
        this.f_StorageAreaCodeOption = [];
        this.isEidtItem = false;
        if (billitem != null || billitem != undefined) {
            this.isEidtItem = true;
            this.itemid = billitem.id;
            this.editBill = billitem;
            //  billitem.f_Sort = 0;
            this._billService.getStorageAreaByWarehouseCode(billitem.f_WarehouseCode).subscribe(result => {
                this.f_StorageAreaCodeOption[0] = result.items.map(e => {
                    return {
                        lable: e.displayText,
                        value: e.value
                    };
                });
                this.miliOutBillList.push(billitem);
            });
            console.log(this.miliOutBillList);
        }
        this.optionInLeaderPush = undefined;
        this.optionInAccountingPush = undefined;
        this.optionOutKeeperPush = undefined;
        this._billService.getToolingTransferBaseForEdit(id).subscribe(result => {
            this.billbase = result;

            if (id != null || id != undefined) {
                this.f_OperatorDate = result.f_OperatorDate.toDate();
                this.billName = "编辑：" + result.f_BillCode;

                this.setSelectedOutDept(result.f_ToDept, result.f_ToDeptId, result.f_OutStoreman, result.f_OutStoremanId);
                this.setSelectedInLeader(result.f_InLeader, result.f_InLeaderId);
                this.setSelectedInAccount(result.f_InAccount, result.f_InAccountId);
                this.setSelectedOutKeeper(result.f_OutStoreman, result.f_OutStoremanId);

            } else {
                this.billName = "新建";
                if (this.selectOutDept != null && this.selectOutDept != undefined) {
                    this.changeInAccounting({ value: this.selectOutDept });
                }
            }

            this.modal.show();
        });
    }
    // //新增/编辑
    // show(id?: string): void {
    //     this.billbase = new Stock_ToolingTransferBaseEditDto();
    //     this.miliOutBillList = new Array<Stock_ToolingTransferItemListDto>();
    //     this.f_OperatorDate = new Date();
    //     this.closed = false;
    //     this.active = true;
    //     this.billid = id;
    //     if (id == undefined) {
    //         this.billbase = new Stock_ToolingTransferBaseEditDto();
    //         // this.billbase.f_OutDeptName = this.f_currentDeptName;
    //         this.modal.show();
    //     } else {
    //         this._billService.getToolingTransferBaseForEdit(id).subscribe(result => {
    //             this.billbase = result;
    //             // this.f_OperatorDate = this.billbase.f_OperatorDate.toDate();
    //             //this.f_ToOperatorDate = this.billbase.f_ToOperatorDate.toDate();
    //             this.modal.show();
    //         });
    //     }
    // }
    //从台帐新增调拨数据
    showList(selectedAccounts: Array<Stock_AccountBaseListDto>): void {
        this.billbase = new Stock_ToolingTransferBaseEditDto();
        this.f_OperatorDate;
        this.active = true;
        this.addAccoutInfo(selectedAccounts);
        this.modal.show();
    }
    close(): void {
        this.active = false;
        if (this.optionInLeaderPush) {
            this.optionInLeader.splice(this.optionInLeader.indexOf(this.optionInLeaderPush), 1);
            this.optionInLeaderPush = undefined;
        }
        if (this.optionInAccountingPush) {
            this.optionInAccounting.splice(this.optionInAccounting.indexOf(this.optionInAccountingPush), 1);
            this.optionInAccountingPush = undefined;
        }
        if (this.optionOutKeeperPush) {
            this.optionOutKeeper.splice(this.optionOutKeeper.indexOf(this.optionOutKeeperPush), 1);
            this.optionOutKeeperPush = undefined;
        }
        this.modal.hide();
    }
    getqccard(event) {
        //this.qccard = event;
    }
    delete() {
        if (!this.selectedBill) {
            this.notify.error('请先勾选对应的工装信息');
            return;
        }
        let milioutbill = new Stock_ToolingTransferItemListDto();
        milioutbill = _.filter(this.miliOutBillList, { f_MaterialCode: this.selectedBill.f_MaterialCode })[0];
        _.remove(this.miliOutBillList, milioutbill);
        this.selectedBill = null;
    }
    //加载台帐信息
    addAccoutInfo(event: Array<Stock_AccountBaseListDto>) {
        if (event) {
            event.forEach(element => {
                if (!this.miliOutBillList.find(e => element.f_MaterialCode == e.f_MaterialCode)) {
                    let milioutbill = new Stock_ToolingTransferItemListDto();
                    milioutbill.f_MaterialCode = element.f_MaterialCode;
                    milioutbill.f_MaterialName = element.f_MaterialName;
                    /* milioutbill.f_WarehouseName = element.f_WarehouseName; */
                    milioutbill.f_UnitPrice = element.f_Price;
                    milioutbill.f_Unit = element.f_UnitId;
                    milioutbill.f_AccountId = element.id;
                    /* milioutbill.f_WarehouseCode = element.f_WarehouseCode;
                    milioutbill.f_WarehouseName = element.f_WarehouseName;
                    milioutbill.f_StorageAreaCode = element.f_StorageAreaCode; */
                    milioutbill.f_RealUsable = element.f_RealUsable;
                    milioutbill.f_InventSerialID = element.f_InventSerialID;
                    milioutbill.f_Precision = element.f_Precision;
                    milioutbill.f_InventSerialID = element.f_InventSerialID;

                milioutbill.f_CAL_ToolingPictureId = element.f_CAL_ToolingPictureId;
                milioutbill.f_CAL_ProductModel = element.f_CAL_ProductModel;
                milioutbill.f_CAL_ProductPictureId = element.f_CAL_ProductPictureId;    
                milioutbill.f_CAL_ToolingWeight = element.f_CAL_ToolingWeight;
                milioutbill.f_CAL_ToolingMaxLoad = element.f_CAL_ToolingMaxLoad;
                milioutbill.f_CAL_ProductModelRemark = element.f_CAL_ProductModelRemark;
                milioutbill.f_CAL_IsAttrition = element.f_CAL_IsAttrition;

              

                    milioutbill.f_TargetRoomName = element.f_WarehouseName;
                    milioutbill.f_TargetRoomCode = element.f_WarehouseCode;
                    milioutbill.f_TargetLocationCode = element.f_StorageAreaCode;
                    if (this.rooms.length > 0) {
                        milioutbill.f_WarehouseCode = this.rooms[0].value;
                    }

                    this.miliOutBillList.push(milioutbill);
                    this.getStorage(this.miliOutBillList.length - 1);
                }
            });
        }
        this.show(this.billid, undefined);
    }
    //保存
    save(): void {
        this.billbase.f_BillName = this.f_currentDeptName + '调拨单';
        //this.billbase.f_ToOperatorDate = moment(this.f_ToOperatorDate).add('hour', 8);
        this.billbase.f_OperatorDate = moment(this.f_OperatorDate).add('hour', 8);
        // this.billbase.f_Dept = _.filter(this.optionOutDept, { value: this.billbase.f_OutDeptName })[0].label;
        // this.billbase.f_ToOperator = _.filter(this.optionInKeeper, {
        //     value: this.billbase.f_ToOperatorId.toString()
        // })[0].label;
        //     this.billbase.f_InLeader = _.filter(this.optionInLeader, {
        //         value: this.billbase.f_InLeaderId.toString()
        //     })[0].label;
        //     this.billbase.f_InAccount = _.filter(this.optionInAccounting, {
        //         value: this.billbase.f_InAccountId.toString()
        //     })[0].label;
        // //   this.billbase.f_ToDept = _.filter(this.optionOutDept,
        // //         { value: this.billbase.f_ToDeptId.toString() })[0].label;
        //     this.billbase.f_OutAccount = _.filter(this.optionOutAccounting, {
        //         value: this.billbase.f_OutAccountId.toString()
        //     })[0].label;
        //     this.billbase.f_OutLeader = _.filter(this.optionOutLeader, {
        //         value: this.billbase.f_OutLeaderId.toString()
        //     })[0].label;
        //     this.billbase.f_OutStoreman = _.filter(this.optionOutKeeper, { value: this.billbase.f_OutStoremanId.toString() })[0].label;
        if (this.miliOutBillList.some(pg => pg.f_RealUsable < pg.f_Quantity)) {
            this.notify.error('调拨数量不能大于实际可用！');
            this.saving = false;
            return;
        }
        if (this.miliOutBillList.some(element => element.f_Quantity == undefined || element.f_Quantity <= 0)) {
            this.notify.error(this.l('调拨数量不正确！'));
            this.saving = false;
            return;
        }
        this.billbase.f_ToDept = this.selectOutDept.label;
        this.billbase.f_InLeader = this.selectInLeader.displayText;
        this.billbase.f_InLeaderId = this.selectInLeader.value;
        this.billbase.f_InAccount = this.selectInAccounting.displayText;
        this.billbase.f_InAccountId = this.selectInAccounting.value;
        this.billbase.f_OutStoreman = this.selectOutKeeper.displayText;
        this.billbase.f_OutStoremanId = this.selectOutKeeper.value;
        this.billbase.f_PlanNumber = this.PlanNumber;
        this.billbase.f_ContractNumber = this.ContractNumber;
        this.primengTableHelper.showLoadingIndicator();
        this._billService
            .createOrUpdateToolingTransferBase(this.billbase)

            .subscribe(result => {
                this.billbase.id = result;
                this._billService.creatWorkflowOfTooling(this.billbase).subscribe(() => {
                    this._billService
                        .creatToolingTransferItems(this.miliOutBillList, result)
                        .pipe(
                            finalize(() => {
                                this.saving = false;
                                this.primengTableHelper.hideLoadingIndicator();
                            })
                        )
                        .subscribe(result => {
                            this.notify.success(this.l('保存成功'));
                            this.miliOutBillList = new Array<Stock_ToolingTransferItemListDto>();
                            this.billbase = new Stock_ToolingTransferBaseEditDto();
                            this.modalSave.emit();
                            this.close();
                            this.primengTableHelper.hideLoadingIndicator();
                        });
                });
            });
    }
    getStorage(index) {
        this._billService.getStorageAreaByWarehouseCode(this.miliOutBillList[index].f_WarehouseCode).subscribe(result => {
            this.f_StorageAreaCodeOption[index] = result.items.map(e => {
                return {
                    lable: e.displayText,
                    value: e.value
                };
            });
            if (this.f_StorageAreaCodeOption[index] != undefined && this.f_StorageAreaCodeOption[index].length > 0) {
                this.miliOutBillList[index].f_StorageAreaCode = this.f_StorageAreaCodeOption[index][0].value;
            }
        });
        // this.miliOutBillList[index].f_TargetRoomCode = this.f_Warehouse;
    }

    accountmodalshow() {
        this.close();

        let timer = setInterval(() => {
            if (this.closed) {
                this.accountShow.emit(this.selectOutDept.label);
                clearInterval(timer);
            }
        }, 50);
    }
    onHidden(event) {
        this.closed = true;
    }
    cancel(): void {
        this.close();
        this.miliOutBillList = new Array<Stock_ToolingTransferItemListDto>();
    }


    setSelectedOutDept(label, value, labelOutKeeper, valueOutKeeper) {
        let t = new LabelValue();
        t.label = label;
        var outDept = this.optionOutDept.filter(p => p.label == label);
        if (outDept.length == 1) {
            t.value = outDept[0].value.value;
        } else {
            t.value = value;
        }
        this.selectOutDept = t;
        this.oldOutDept = this.selectOutDept;

        // this._tranbillService.getRoleUser('工装库存保管员', t.value).subscribe(result => {
        //     this.optionOutKeeper = result.items.map(e => {
        //         return {
        //             label: e.displayText,
        //             value: e
        //         };
        //     });   
        //     if(labelOutKeeper != null){         
        //         this.setSelectedOutKeeper(labelOutKeeper,valueOutKeeper);
        //     }
        // });

    }

    setSelectedInLeader(label, value) {
        if (value == null) return;
        let t = new ComboboxItemDto();
        t.value = value.toString();
        t.displayText = label;
        t.isSelected = false;

        //如果下拉列表中不存在，下拉列表中增加一条 
        let obj = { label: label, value: t };
        let some = this.optionInLeader.some(e => e.value.value == value);
        if (some == false) {
            this.optionInLeader.push(obj);
            this.optionInLeaderPush = obj;
        }

        this.selectInLeader = t;

    }
    setSelectedInAccount(label, value) {
        if (value == null) return;
        let t = new ComboboxItemDto();
        t.value = value.toString();
        t.displayText = label;
        t.isSelected = false;

        //如果下拉列表中不存在，下拉列表中增加一条 
        let obj = { label: label, value: t };
        let some = this.optionInAccounting.some(e => e.value.value == value);
        if (some == false) {
            this.optionInLeader.push(obj);
            this.optionInAccountingPush = obj;
        }

        this.selectInAccounting = t;
    }
    setSelectedOutKeeper(label, value) {
        if (value == null) return;
        let t = new ComboboxItemDto();
        t.value = value.toString();
        t.displayText = label;
        t.isSelected = false;

        //如果下拉列表中不存在，下拉列表中增加一条 
        let obj = { label: label, value: t };
        let some = this.optionOutKeeper.some(e => e.value.value == value);
        if (some == false) {
            this.optionOutKeeper.push(obj);
            this.optionOutKeeperPush = obj;
        }

        this.selectOutKeeper = t;
    }
}
